const { cloud } = getApp();
Page({
  data: { couponList: [] },
  onLoad() {
    this.loadCoupon()
  },
  async loadCoupon() {
    try {
      const res = await cloud.topApi.invoke({
        api: 'taobao.promotion.activity.get',
        authScope: '*'
      });
      let couponList = res.activitys;
      for (let i = 0; i < couponList.length; i++) {
        const res2 = await cloud.topApi.invoke({
          api: 'taobao.promotion.coupons.get',
          authScope: '*',
          data: {
            coupon_id: couponList[i].coupon_id
          }
        });
        couponList[i].denominations = res2.coupons[0].denominations;
        couponList[i].conditions = res2.coupons[0].condition
      }
      this.setData({
        couponList: couponList
      })
    } catch (e) {
      my.alert({ content: 'error ' + e.message })
    }
  },
  async chooseCoupon(e) {
    let index = e.currentTarget.dataset.index;
    let couponInfo = this.data.couponList[index];
    const res = await cloud.application.httpRequest({
      path: '/index.php/index/qn/writeCoupon',
      method: 'POST',
      params: {
        shop_id: getApp().globalData.shop_id,
        coupon_id:couponInfo.coupon_id,
        denominations: couponInfo.denominations,
        conditions: couponInfo.conditions,
        activity_url: couponInfo.activity_url
      }
    })
    my.alert({
      content: '优惠券设置成功，返回之后再次刷新页面可以看到设置效果',
      success: (res) => {
        my.navigateTo({ url: '/pages/index/index' });
      }
    })
  }
});
